package Yki.PaperPlaneClient;

import java.util.List;
import java.util.Map;

import Yki.PaperPlaneClient.Judgement.JudgeValidment;
import Yki.PaperPlaneClient.Requests.BasicRequest;
import Yki.PaperPlaneClient.Requests.LoginRequest;
import Yki.PaperPlaneClient.XML.XMLUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * 登陆界面
 * 
 * @author 吴学维
 *
 */
public class Login extends Activity {

	//public final static String SERVER = "http://222.200.180.9/PaperPlaneServer/";
	public final static String SERVER = "http://10.4.2.219:8080/PaperPlaneServer/";
	private final int LOGIN_FAILED = 0;
	private final int LOGIN_SUCCESS = 1;
	
	private int loginResult;
	
	private Context context;
    private EditText usernameEditText;
    private EditText passwordEditText;
    private ImageView signUpImageView;
    private ImageView loginImageView;
    private String usernameString = "";
    private String passwordString = "";
   
    private int responseUserId;
    
    private ProgressDialog progressDialog;
    
    private Handler mHandler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case LOGIN_FAILED:
				progressDialog.cancel();
				Toast.makeText(Login.this, "登录失败" + loginResult, Toast.LENGTH_LONG).show();
				break;

			case LOGIN_SUCCESS:
				progressDialog.cancel();
				Toast.makeText(Login.this, "登陆成功：" + responseUserId, Toast.LENGTH_LONG).show();
				
				Intent intent = new Intent(context, MainActivity.class);
				intent.putExtra(XMLUtils.TAG_USER_ID, responseUserId);
				intent.putExtra(XMLUtils.TAG_PASSWORD, passwordString);
				startActivity(intent);
				finish();
				break;
			default:
				break;
			}
    	}
    };
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login);
		
        BasicRequest.SetDefaultUrl(SERVER);
        
        context = this;
        
        usernameEditText = (EditText)findViewById(R.id.editTextLoginUsername);
        passwordEditText = (EditText)findViewById(R.id.editTextLoginPassword);

        Typeface typeface = Typeface.createFromAsset(getAssets(), "minishanhu.ttf");
        usernameEditText.setTypeface(typeface);
        passwordEditText.setTypeface(typeface);
        
        signUpImageView = (ImageView)findViewById(R.id.ImageViewLoginSignUp);
        loginImageView = (ImageView)findViewById(R.id.ImageViewLoginLogin);
        
        loginImageView.setOnClickListener(loginListener);
        signUpImageView.setOnClickListener(registerListener);
    }
    
    
    private boolean isAllValid() {
//    	if(!JudgeValidment.isusernameValid(usernameString)){
//			Toast.makeText(Login.this, 
//					"请输入正确的账号（即您的邮箱地址）!", Toast.LENGTH_LONG).show();
//			return false;
//    	}
    	if(!JudgeValidment.isPasswdValid(passwordString)){
			Toast.makeText(Login.this, 
					"密码长度应为5-20位，请检查密码输入是否正确!", Toast.LENGTH_LONG).show();
			return false;
    	}
    	return true;    		
    }
    

    // 登陆按钮的监听。
    // 在判断用户输入字段有效后调用login函数登陆。
    OnClickListener loginListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			usernameString = usernameEditText.getText().toString();
			passwordString = passwordEditText.getText().toString();
			
			if(isAllValid())
				login();
		}
	};

	// 注册按钮的监听，跳转注册界面
	OnClickListener registerListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intentRegister = new Intent(context, Register.class);
			startActivity(intentRegister);			
		}
	};
    
	OnClickListener skipButtonOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(context, MainActivity.class);
			startActivity(intent);			
		}
	};

	/**
     * 开启线程，进行登录
     */
    private void login() {
    	progressDialog = new ProgressDialog(this);
    	progressDialog.setTitle("请等待");
    	progressDialog.setMessage("正在为您登录...");
    	progressDialog.show();  
    	new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub

				// 布尔变量success用来记录登陆状态，true为成功
				boolean success = false; 
				LoginRequest loginRequest = new LoginRequest();
				loginRequest.setUserInfo(usernameString, passwordString);
				List<Map<String, Object>> result = loginRequest.GetRequestResult();
				// test!默认登陆成功。
				success = loginRequest.isSuccess();
				loginResult = loginRequest.getStatusCode();
				
				//登录成功以后，跳转主界面
				if(success && result != null && result.size() > 0) {
					responseUserId = Integer.valueOf((String) result.get(0).get(XMLUtils.TAG_USER_ID));
					Message msg = new Message();
					msg.what = LOGIN_SUCCESS;
					mHandler.sendMessage(msg);
				}
				else {
					Message msg = new Message();
					msg.what = LOGIN_FAILED;
					//mHandler.sendMessage(msg);
					Intent intent = new Intent(context, MainActivity.class);
					intent.putExtra(XMLUtils.TAG_USER_ID, responseUserId);
					intent.putExtra(XMLUtils.TAG_PASSWORD, passwordString);
					startActivity(intent);
				}
			}
		}).start();
    };
}
